<template>
  <div class="carousel-container">
    <div class="imgList" ref="imgListRef">
      <a href="#" v-for="(item, i) in images" :key="i" class="imgs">
        <img :src="item" alt="" />
      </a>
      <div class="indicator" ref="indicatorRef">
        <span
          v-for="(item, i) in images"
          :key="i"
          class="indicator-item"
          @click="moveTo(i)"
        ></span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, onBeforeUnmount, ref } from "vue";
import { createAnimation } from "../utils/animate.js";

const images = [
  "https://picsum.photos/id/1/2000/500",
  "https://picsum.photos/id/2/2000/500",
  "https://picsum.photos/id/3/2000/500",
];

let curIndex = ref(0);
let intervalId;

const imgListRef = ref(null);
const indicatorRef = ref(null);

/**
 * 根据curIndex设置指示器状态
 */
function setIndicatorStatus() {
  const active = indicatorRef.value.querySelector(".active");
  if (active) {
    active.classList.remove("active");
  }
  indicatorRef.value.children[curIndex.value].classList.add("active");
}

/**
 * 将轮播图从当前位置切换到 newIndex 位置
 * @param {number} newIndex 新位置索引
 */
function moveTo(newIndex) {
  const carouselList = imgListRef.value;
  const from = parseFloat(carouselList.style.marginLeft) || 0;
  const to = -newIndex * 2000;
  const totalMS = 500;
  createAnimation({
    from,
    to,
    totalMS,
    onmove: function (n) {
      carouselList.style.marginLeft = n + "px";
    },
  });

  curIndex.value = newIndex;
  setIndicatorStatus();
}

onMounted(() => {
  const carouselList = imgListRef.value;
  const indicator = indicatorRef.value;
  setIndicatorStatus(); //

  intervalId = setInterval(() => {
    const newIndex = (curIndex.value + 1) % images.length;
    moveTo(newIndex);
  }, 3000);
});

onBeforeUnmount(() => {
  clearInterval(intervalId);
});
</script>

<style scoped>
.carousel-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.imgList {
  width: 8000px;
  height: 100%;
}

img {
  object-fit: cover;
  float: left;
}

.indicator {
  position: absolute;
  width: 100%;
  left: 0;
  bottom: 50px;
  height: 30px;
  text-align: center;
}
.indicator-item {
  display: inline-block;
  width: 10px; /* 圆圈的宽度 */
  height: 10px; /* 圆圈的高度 */
  border-radius: 50%; /* 设置圆形 */
  background-color: rgb(52, 52, 52);
  cursor: pointer;
  margin: 0 5px;
}
.indicator-item.active {
  background: dodgerblue;
}

.active {
  background-color: aqua;
}
</style>
